from machine import Pin
from umqtt.simple import MQTTClient
import time
import dht

import network
# 等待网络连接
def wait_for_wifi_connection():
    wlan = network.WLAN(network.STA_IF) # 创建接口
    wlan.active(True)       # 激活接口
    wlan.scan()             # 扫描当前热点
    wlan.connect('1439', '234567890') # 连接到指定wifi，其中ssid为wifi名，key为wifi密码
    # wlan.config('mac')      # 获取连接后的mac地址 
    network_config = wlan.ifconfig()         # 获取连接后的IP/netmask/gw/DNS等地址信息
    #print(network_config)

    # 定义 灯泡引脚
    d15 = Pin(15,Pin.OUT)
    d15.value(0) # 默认不亮灯

    while not wlan.isconnected():
        continue
    print("网络已连接！")

wait_for_wifi_connection()


# mqtt配置信息
topic_temp = "base/temp"
topic_hum = "base/hum"
topic_temphum = "base/temp_hum"

def connect2Broker():
    global topic_temp,topic_hum
    # 第一个参数为client_id，要求不能重复，后面的为MQTT服务器IP地址
    client = MQTTClient("123456","192.168.10.29")
    client.connect()
    return client

client = connect2Broker()


dht11 = dht.DHT11(Pin(2))

while True:
    time.sleep(2)
    try:
        dht11.measure() # 测量数据
    
        temp = dht11.temperature()  # 获取温度
        
        client.publish(topic_temp,str(temp)) # 发布温度
        
        hum = dht11.humidity() # 获取湿度
        
        client.publish(topic_hum,str(hum)) # 发布湿度
        
        # 同时发布温度和湿度
        client.publish(topic_temphum,"{},{}".format(temp,hum)) # 发布湿度
    except Exception as e:
        print(e)
        wait_for_wifi_connection()
        client = connect2Broker()
        continue

    print(temp,hum)


